<?php
class BaseReCaptchaForm extends sfFormSymfony {
    public function configure() {
        sfContext::getInstance()->getLogger()->debug("BaseReCaptchaForm: configure");
        if(!$this->offsetExists('_recaptcha_form'))
            $this->setWidget('_recaptcha_form', new sfWidgetFormReCaptcha());

        $this->setWidget('_recaptcha_challenge', new sfWidgetFormInputHidden());
        $this->setWidget('_recaptcha_response', new sfWidgetFormInputHidden());
        
        $this->setValidator('_recaptcha_challenge', new sfValidatorString(array(
            'required' => 'true',
        )));
        $this->setValidator('_recaptcha_response', new sfValidatorString(array(
            'required' => 'true',
        )));
        $this->setValidator('_recaptcha_form', new sfValidatorBoolean(array('required' => true)));
    }
    
    public function bind(array $taintedValues = null, array $taintedFiles = null)
    {
        $hasCaptcha = $this->getWidget('_recaptcha_form');
        if(!empty($hasCaptcha))
        {
            $request = sfContext::getInstance()->getRequest();

            if($request->hasParameter('recaptcha_challenge_field'))
                $taintedValues['_recaptcha_challenge'] = $request->getParameter('recaptcha_challenge_field');
            else
                unset($taintedValues['_recaptcha_challenge']);
           if($request->hasParameter('recaptcha_response_field'))
                $taintedValues['_recaptcha_response'] = $request->getParameter('recaptcha_response_field');
            else
                unset($taintedValues['_recaptcha_challenge']);
            $recaptcha = $this->getWidget('_recaptcha_form')->getReCaptcha();
            $recaptcha->checkAnswer($request);
           if($recaptcha->isValid())
                $taintedValues['_recaptcha_form'] = 'on';
            else
                unset($taintedValues['_recaptcha_form']);
        }
        parent::bind($taintedValues, $taintedFiles);
    }
    
}